import { defineStore } from "pinia";
import type {IStateType,ILoginFormType,ILoginResultType,} from "@/typings/userType";
import { doUserLogin } from "@/api/userApi";

const useUserStore = defineStore("user", {
    persist:{
        storage:window.sessionStorage
    },
  state: () =>
    ({
      userinfo: {
        uid: 0,
        username: "",
        token: "",
      },
    } as IStateType),
    getters:{
      token:state => state.userinfo.token || ''
    },
    actions: {
      // 修改state中信息，将传入的参数赋值给存储的表单信息
      setUserInfo(info: ILoginResultType) {
        this.userinfo = info;
      },
      // 异步网络请求，将用户表单数据作为参数传入
      async fetchLoginAction(userData: ILoginFormType) {
      // 请求用户登录信息，将其返回值赋值给 ret 
      // 如果请求成功，就执行setUserInfo,将返回结果中的data作为参数传入
          let ret = await doUserLogin(userData)
          if(ret.code === 0){
              this.setUserInfo(ret.data)
          }
          return ret.code
      },
    },
});

// 然后将此方法导出
export default useUserStore;